package com.winit.cloudlink;

import com.winit.cloudlink.config.ApplicationOptions;
import com.winit.ubarrier.common.SwitchCommand;
import com.winit.ubarrier.common.util.ClassUtils;
import com.winit.ubarrier.common.util.Nets;
import com.winit.ubarrier.jmx.agent.JmxAbstractSwitcher;
import com.winit.ubarrier.jmx.agent.UbarrierAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by stvli on 2017/6/20.
 */
public class CloudlinkSwitcher extends JmxAbstractSwitcher {
	private static final Logger logger = LoggerFactory.getLogger(CloudlinkSwitcher.class);
	public static final String NAME = "cloudlink";
	public static final String DEFAULT_UBARRIER_VIRTUAL_HOST = "ubarrier";
	private static CloudlinkSwitcher instance;

	private Cloudlink cloudlink;
	private ApplicationOptions applicationOptions;

	private final AtomicBoolean initialized = new AtomicBoolean(false);
	private final ClassLoader cl;

	private CloudlinkSwitcher(Cloudlink cloudlink) {
		this.cl = ClassUtils.getClassLoader();
		this.cloudlink = cloudlink;
		this.applicationOptions = cloudlink.getMetadata().getApplicationOptions();
	}

	public static synchronized CloudlinkSwitcher getInstance(Cloudlink cloudlink) {
		if (CloudlinkSwitcher.instance == null) {
			CloudlinkSwitcher.instance = new CloudlinkSwitcher(cloudlink);
			UbarrierAgent.getInstance().registerSwitcher(CloudlinkSwitcher.instance);
			CloudlinkSwitcher.instance.initialized.set(true);
		}
		return CloudlinkSwitcher.instance;
	}

	@Override
	public String name() {
		return NAME;
	}

	@Override
	protected void executeInternel(final SwitchCommand command) {
		if (!needSwitch(command)) {
			logger.info("Cloudlink无需切换。");
			return;
		}
		logger.info("Cloudlink开始切换到{}模式...", command.getGrayMode().name());
		if (isGray(command)) {
			logger.info("Cloudlink开始停止消费消息...");
			applicationOptions.setAutoStartContainer(false);
			cloudlink.deactive();
			logger.info("Cloudlink已停止消费消息。");
		} else {
			logger.info("Cloudlink开始启动消费消息...");
			applicationOptions.setAutoStartContainer(true);
			cloudlink.active();
			logger.info("Cloudlink已启动消费消息。");
		}
		logger.info("Cloudlink已切换到{}模式。", command.getGrayMode().name());
	}


	protected boolean needSwitch(final SwitchCommand command) {
		if (command.getGrayMode().equals(this.grayMode)) {
			return false;
		}
		String host = Nets.getLocalHost();
		switch (command.getGrayMode()) {
			case GNONE:
				return true;
			case GA:
				return command.getAgroupHosts().contains(host);
			case GB:
				return command.getBgroupHosts().contains(host);
			default:
				return false;
		}
	}
}
